<template>
  <div class="mine-container">
    <!-- 第一部分：激活码输入界面 -->
    <div v-if="!isLoggedIn" class="activation-section">
      <div class="activation-card">
        <h2>激活码登录</h2>
        
        <div class="activation-form">
          <div class="form-group">
            <label>激活码</label>
            <input 
              v-model="activationCode" 
              type="text" 
              placeholder="请输入激活码" 
              @keyup.enter="handleActivation"
            />
          </div>
          <button @click="handleActivation" :disabled="activationLoading" class="btn-primary">
            {{ activationLoading ? '激活中...' : '激活账号' }}
          </button>
        </div>

        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>
      </div>
    </div>

    <!-- 第二部分：权限管理界面 -->
    <div v-else class="admin-section">
      <!-- 用户信息头部 -->
      <div class="user-header">
        <div class="user-info">
          <div class="avatar">{{ getUserInitial() }}</div>
          <div class="user-details">
            <h3>{{ userInfo.username || '用户' }}</h3>
            <p class="role">{{ getRoleText(userInfo.role) }}</p>
            <p class="status">{{ getStatusText(userInfo.status) }}</p>
          </div>
        </div>
        <button @click="handleLogout" class="btn-logout">退出登录</button>
      </div>

      <!-- 超级管理员功能 -->
      <div v-if="userInfo.role === 'super_admin'" class="super-admin-panel">
        <h3>超级管理员控制台</h3>
        
        <!-- 创建推广管理员 -->
        <div class="function-card">
          <h4>创建推广管理员</h4>
          <div class="form-row">
            <input v-model="newPromotionAdmin.trial_days" type="number" placeholder="试用天数" />
            <input v-model="newPromotionAdmin.subscription_days" type="number" placeholder="订阅天数" />
            <input v-model="newPromotionAdmin.max_users" type="number" placeholder="最大用户数" />
            <button @click="createPromotionAdmin" class="btn-primary">创建推广管理员</button>
          </div>
        </div>

        <!-- 推广管理员列表 -->
        <div class="function-card">
          <h4>推广管理员列表</h4>
          <div class="admin-list">
            <div v-for="admin in promotionAdmins" :key="admin.id" class="admin-item">
              <div class="admin-info">
                <span class="username">{{ getDisplayName(admin.username) }}</span>
                <span class="status-badge" :class="admin.status">{{ getStatusText(admin.status) }}</span>
              </div>
              <div class="admin-actions">
                <button @click="extendTrial(admin.id)" class="btn-small">延长试用期</button>
                <button @click="toggleAdminStatus(admin)" class="btn-small">
                  {{ admin.status === 'active' ? '禁用' : '启用' }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 推广管理员功能 -->
      <div v-if="userInfo.role === 'promotion_admin'" class="promotion-admin-panel">
        <h3>推广管理员控制台</h3>
        
        <!-- 创建付费激活码 -->
        <div class="function-card">
          <h4>创建付费激活码</h4>
          <div class="form-row">
            <input v-model="newPaidCode.trial_days" type="number" placeholder="试用天数" />
            <input v-model="newPaidCode.subscription_days" type="number" placeholder="订阅天数" />
            <input v-model="newPaidCode.max_users" type="number" placeholder="最大用户数" />
            <button @click="createPaidCode" class="btn-primary">创建付费激活码</button>
          </div>
        </div>

        <!-- 付费激活码列表 -->
        <div class="function-card">
          <h4>付费激活码列表</h4>
          <div class="code-list">
            <div v-for="code in paidCodes" :key="code.id" class="code-item">
              <div class="code-info">
                <span class="code-text">{{ code.code }}</span>
                <span class="code-status" :class="code.is_valid ? 'valid' : 'invalid'">
                  {{ code.is_valid ? '有效' : '已使用' }}
                </span>
              </div>
              <div class="code-details">
                <span>试用期: {{ code.trial_days }}天</span>
                <span>订阅期: {{ code.subscription_days }}天</span>
                <span>已用: {{ code.used_count }}/{{ code.max_users }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 消息提示 -->
    <div v-if="message" class="message" :class="messageType">
      {{ message }}
    </div>
  </div>
</template>

<script>
export default {
  name: 'Mine',
  data() {
    return {
      // 登录状态
      isLoggedIn: false,
      userInfo: {},
      token: null,
      activationCode: '',
      activationLoading: false,
      errorMessage: '',
      
      // 超级管理员数据
      promotionAdmins: [],
      newPromotionAdmin: {
        trial_days: 30,
        subscription_days: 365,
        max_users: 10
      },
      
      // 推广管理员数据
      paidCodes: [],
      newPaidCode: {
        trial_days: 7,
        subscription_days: 30,
        max_users: 1
      },
      
      // 消息
      message: '',
      messageType: 'success'
    }
  },
  
  mounted() {
    this.checkLoginStatus()
  },
  
  methods: {
    // 检查登录状态
    checkLoginStatus() {
      const token = localStorage.getItem('token')
      if (token) {
        this.token = token
        this.loadUserInfo()
      }
    },
    
    // 加载用户信息
    async loadUserInfo() {
      try {
        const response = await fetch('/api/user/profile', {
          headers: { 
            'Authorization': `Bearer ${this.token}`,
            'Content-Type': 'application/json'
          }
        })
        
        if (response.ok) {
          const data = await response.json()
          if (data.success) {
            this.userInfo = data.data
            this.isLoggedIn = true
            this.loadRoleData()
          }
        } else {
          this.logout()
        }
      } catch (error) {
        console.error('加载用户信息失败:', error)
        this.logout()
      }
    },
    
    // 根据角色加载数据
    loadRoleData() {
      if (this.userInfo.role === 'super_admin') {
        this.loadPromotionAdmins()
      } else if (this.userInfo.role === 'promotion_admin') {
        this.loadPaidCodes()
      }
    },
    
    // 处理激活
    async handleActivation() {
      if (!this.activationCode.trim()) {
        this.errorMessage = '请输入激活码'
        return
      }
      
      this.activationLoading = true
      this.errorMessage = ''
      
      try {
        console.log('🔍 开始激活流程，激活码:', this.activationCode)
        
        const response = await fetch('/api/auth/activate', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            code: this.activationCode
          })
        })
        
        const data = await response.json()
        console.log('✅ API响应:', data)
        
        if (data.success) {
          this.token = data.data.token
          this.userInfo = data.data.user
          this.isLoggedIn = true
          localStorage.setItem('token', this.token)
          this.activationCode = ''
          this.errorMessage = ''
          this.showMessage('激活成功', 'success')
          this.loadRoleData()
        } else {
          this.errorMessage = data.message || '激活失败'
        }
      } catch (error) {
        console.error('❌ API调用失败:', error)
        this.errorMessage = '激活失败，请检查网络连接'
      } finally {
        this.activationLoading = false
      }
    },
    
    // 退出登录
    handleLogout() {
      this.logout()
    },
    
    logout() {
      this.isLoggedIn = false
      this.userInfo = {}
      this.token = null
      this.activationCode = ''
      this.errorMessage = ''
      this.promotionAdmins = []
      this.paidCodes = []
      localStorage.removeItem('token')
      this.showMessage('已退出登录', 'success')
    },
    
    // 超级管理员功能
    async loadPromotionAdmins() {
      try {
        const response = await fetch('/api/admin/users?role=promotion_admin', {
          headers: { 
            'Authorization': `Bearer ${this.token}`,
            'Content-Type': 'application/json'
          }
        })
        
        if (response.ok) {
          const data = await response.json()
          if (data.success) {
            this.promotionAdmins = data.data.users
          }
        }
      } catch (error) {
        this.showMessage('加载推广管理员列表失败', 'error')
      }
    },
    
    async createPromotionAdmin() {
      try {
        const response = await fetch('/api/admin/activation-codes', {
          method: 'POST',
          headers: { 
            'Authorization': `Bearer ${this.token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            code_type: 'promotion_admin',
            role: 'promotion_admin',
            trial_days: this.newPromotionAdmin.trial_days,
            subscription_days: this.newPromotionAdmin.subscription_days,
            max_users: this.newPromotionAdmin.max_users,
            description: '推广管理员激活码'
          })
        })
        
        if (response.ok) {
          const data = await response.json()
          if (data.success) {
            this.showMessage('推广管理员激活码创建成功', 'success')
            this.newPromotionAdmin = { trial_days: 30, subscription_days: 365, max_users: 10 }
          }
        }
      } catch (error) {
        this.showMessage('创建推广管理员激活码失败', 'error')
      }
    },
    
    async extendTrial(adminId) {
      const days = prompt('请输入延长的天数:')
      if (!days || isNaN(days)) return
      
      try {
        const response = await fetch(`/api/admin/users/${adminId}/extend-trial`, {
          method: 'POST',
          headers: { 
            'Authorization': `Bearer ${this.token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ days: parseInt(days) })
        })
        
        if (response.ok) {
          const data = await response.json()
          if (data.success) {
            this.showMessage('延长试用期成功', 'success')
            this.loadPromotionAdmins()
          }
        }
      } catch (error) {
        this.showMessage('延长试用期失败', 'error')
      }
    },
    
    async toggleAdminStatus(admin) {
      const newStatus = admin.status === 'active' ? 'suspended' : 'active'
      try {
        const response = await fetch(`/api/admin/users/${admin.id}/status`, {
          method: 'PUT',
          headers: { 
            'Authorization': `Bearer ${this.token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ status: newStatus })
        })
        
        if (response.ok) {
          const data = await response.json()
          if (data.success) {
            this.showMessage('状态更新成功', 'success')
            this.loadPromotionAdmins()
          }
        }
      } catch (error) {
        this.showMessage('状态更新失败', 'error')
      }
    },
    
    // 推广管理员功能
    async loadPaidCodes() {
      try {
        const response = await fetch('/api/promotion/activation-codes', {
          headers: { 
            'Authorization': `Bearer ${this.token}`,
            'Content-Type': 'application/json'
          }
        })
        
        if (response.ok) {
          const data = await response.json()
          if (data.success) {
            this.paidCodes = data.data.codes
          }
        }
      } catch (error) {
        this.showMessage('加载付费激活码失败', 'error')
      }
    },
    
    async createPaidCode() {
      try {
        const response = await fetch('/api/promotion/activation-codes', {
          method: 'POST',
          headers: { 
            'Authorization': `Bearer ${this.token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            code_type: 'paid_user',
            role: 'user',
            trial_days: this.newPaidCode.trial_days,
            subscription_days: this.newPaidCode.subscription_days,
            max_users: this.newPaidCode.max_users,
            description: '付费用户激活码'
          })
        })
        
        if (response.ok) {
          const data = await response.json()
          if (data.success) {
            this.showMessage('付费激活码创建成功', 'success')
            this.newPaidCode = { trial_days: 7, subscription_days: 30, max_users: 1 }
            this.loadPaidCodes()
          }
        }
      } catch (error) {
        this.showMessage('创建付费激活码失败', 'error')
      }
    },
    
    // 工具方法
    getUserInitial() {
      if (this.userInfo.username) {
        return this.userInfo.username.charAt(0).toUpperCase()
      }
      return 'U'
    },
    
    getRoleText(role) {
      const roleMap = {
        'super_admin': '超级管理员',
        'promotion_admin': '推广管理员',
        'user': '普通用户'
      }
      return roleMap[role] || role
    },
    
    getStatusText(status) {
      const statusMap = {
        'active': '正常',
        'inactive': '未激活',
        'suspended': '已禁用'
      }
      return statusMap[status] || status
    },
    
    getDisplayName(username) {
      if (!username) return '未命名用户'
      const match = username.match(/^user_(\d+)_(\d+)$/)
      if (match) {
        return `用户${match[1]}`
      }
      return username
    },
    
    showMessage(text, type = 'success') {
      this.message = text
      this.messageType = type
      setTimeout(() => {
        this.message = ''
      }, 3000)
    }
  }
}
</script>

<style scoped>
.mine-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  min-height: 100vh;
  background: #f5f5f5;
}

/* 第一部分：激活码输入界面 */
.activation-section {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 80vh;
}

.activation-card {
  background: white;
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
}

.activation-card h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.activation-form {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #555;
  font-weight: 500;
}

.form-group input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
}

.btn-primary {
  width: 100%;
  padding: 12px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.3s;
}

.btn-primary:hover:not(:disabled) {
  background: #0056b3;
}

.btn-primary:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.error-message {
  color: #dc3545;
  text-align: center;
  margin-top: 10px;
  padding: 10px;
  background: #f8d7da;
  border-radius: 6px;
  border: 1px solid #f5c6cb;
}

/* 第二部分：权限管理界面 */
.admin-section {
  margin-top: 20px;
}

.user-header {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  margin-bottom: 30px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar {
  width: 60px;
  height: 60px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: bold;
}

.user-details h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
}

.user-details p {
  margin: 4px 0;
  font-size: 14px;
  opacity: 0.9;
}

.btn-logout {
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 6px;
  cursor: pointer;
  transition: background 0.3s;
}

.btn-logout:hover {
  background: rgba(255, 255, 255, 0.3);
}

/* 功能面板 */
.super-admin-panel,
.promotion-admin-panel {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.super-admin-panel h3,
.promotion-admin-panel h3 {
  margin: 0 0 30px 0;
  color: #333;
  font-size: 24px;
  text-align: center;
}

.function-card {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.function-card h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 18px;
}

.form-row {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.form-row input {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  flex: 1;
  min-width: 120px;
}

.form-row button {
  padding: 10px 20px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  white-space: nowrap;
}

.form-row button:hover {
  background: #0056b3;
}

/* 列表样式 */
.admin-list,
.code-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.admin-item,
.code-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.admin-info,
.code-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.username {
  font-weight: 500;
  color: #333;
}

.code-text {
  font-family: monospace;
  background: #e9ecef;
  padding: 4px 8px;
  border-radius: 4px;
  font-weight: 500;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.active {
  background: #e8f5e8;
  color: #2e7d32;
}

.status-badge.suspended {
  background: #ffebee;
  color: #c62828;
}

.code-status.valid {
  background: #e8f5e8;
  color: #2e7d32;
}

.code-status.invalid {
  background: #ffebee;
  color: #c62828;
}

.admin-actions {
  display: flex;
  gap: 10px;
}

.btn-small {
  padding: 6px 12px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.btn-small:hover {
  background: #0056b3;
}

.code-details {
  display: flex;
  gap: 20px;
  color: #666;
  font-size: 14px;
}

/* 消息提示 */
.message {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 15px 20px;
  border-radius: 6px;
  color: white;
  font-weight: 500;
  z-index: 1001;
  animation: slideIn 0.3s ease;
}

.message.success {
  background: #28a745;
}

.message.error {
  background: #dc3545;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .mine-container {
    padding: 10px;
  }
  
  .user-header {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }
  
  .form-row {
    flex-direction: column;
  }
  
  .admin-item,
  .code-item {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .admin-actions {
    width: 100%;
    justify-content: space-between;
  }
}
</style> 